package com.study.framework;

import java.util.NoSuchElementException;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;

public abstract class HelperBase {


	protected final ApplicaionManager manager;
	protected WebDriver driver;
	public boolean acceptNextAlert = true;

	public HelperBase(ApplicaionManager manager){
		this.manager = manager;
		this.driver = manager.driver;
	}
    
	public boolean isElementPresent(By by) {
		try {
			findElement(by);
			return true;
		} catch (NoSuchElementException e) {
			return false;
		}
	}

	public String closeAlertsAndGetItsText() {
		try {
		  Alert alert = driver.switchTo().alert();
		  if (acceptNextAlert) {
			  alert.accept();
		  } else {
			  alert.dismiss();
		  }
			return alert.getText();
		} finally {
			acceptNextAlert = true;
		}
	}

	protected void type(By locator, String text) {
		if (text != null) {
		findElement(locator).clear();
		findElement(locator).sendKeys(text);
		}
	}

	protected void click(By locator) {
		findElement(locator).click();
	}

	private WebElement findElement(By locator) {
		return driver.findElement(locator);
	}
	
    protected void selectByText(By locator, String text) {
    	if (text != null) {
		new Select( findElement(locator)).selectByVisibleText(text);
    	}
   
    }
}
